#include "zyf_time.h"
#include "zyf_marcos.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif

static const char* zyf_d_mon[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

time_t zyf_net_time()
{
	time_t rtime = 0;
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	ZYF_RET(fd < 0, rtime);
	char buf[128] = {0};
	struct tm now;
	char tmp[5] = {0};
	const char* pdate = NULL;
	struct timeval timeout = {3, 0}; // 设置3s的超时
	struct hostent* host = gethostbyname("www.beijing-time.org");
	struct sockaddr_in addr;
	ssize_t ret;
	ZYF_GOTO(!host, do_err);

	setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));

	addr.sin_port = htons(80);
	addr.sin_family = AF_INET;
	memcpy(&addr.sin_addr.s_addr, host->h_addr, host->h_length);
	ret = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
	ZYF_GOTO(ret < 0, do_err);
	ret = write(fd, "h\n", 2);
	ZYF_GOTO(ret < 2, do_err);
	ret = read(fd, buf, sizeof(buf) - 1);
	if (ret > 35) {
		//Date: Thu, 09 Apr 2015 05:49:14 GMT
		//      6    11 14  18   23 26 29
		pdate = strstr(buf, "Date");
		memcpy(tmp, pdate + 18, 4);
		now.tm_year = atoi(tmp) - 1900;

		tmp[3] = 0;
		memcpy(tmp, pdate + 14, 3);
		for (ret = 0; ret < 12; ++ret) {
			if (!strcmp(tmp, zyf_d_mon[ret]))
				break;
		}
		now.tm_mon = ret;

		tmp[2] = 0;
		memcpy(tmp, pdate + 11, 2);
		now.tm_mday = atoi(tmp);

		memcpy(tmp, pdate + 23, 2);
		now.tm_hour = atoi(tmp);
		memcpy(tmp, pdate + 26, 2);
		now.tm_min = atoi(tmp);
		memcpy(tmp, pdate + 29, 2);
		now.tm_sec = atoi(tmp);
		rtime = mktime(&now) + 28800;
	}
do_err:
	close(fd);
	return rtime;
}

#ifdef __cplusplus
} /* end extern C */
#endif
